package red.uec.controller.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import red.uec.jwt.JwtExpireException;
import red.uec.jwt.JwtHelper;
import red.uec.jwt.JwtPayload;
import red.uec.jwt.JwtVerifyException;
import red.uec.model.RestfulResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwt = request.getHeader("jwt");
        if(StringUtils.isBlank(jwt)){
            doResponse(response, new RestfulResponse().fail("未登录"));
            return false;
        }
        log.debug("jwt: {}", jwt);

        try {
            // 验证jwt
            JwtPayload jwtPayload = jwtHelper.verifyToken(jwt);
            JwtHelper.setJwtPayload(jwtPayload);

            // TODO： 验证登录超时

            // 验证登录互斥-未来需要时添加
            // ...
        }catch (JwtVerifyException|JwtExpireException e){
            log.error(e.getMessage(), e);
            doResponse(response, new RestfulResponse().fail("未登录"));
            return false;
        }

        return true;
    }

    private void doResponse(HttpServletResponse httpServletResponse, RestfulResponse restfulResponse) throws Exception{
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter printWriter = httpServletResponse.getWriter();
        new ObjectMapper().writeValue(printWriter, restfulResponse);
    }
}
